package ch09.game;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FileReaderManger2 {

    public static void save(Position position){
        try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("data/game4.save"))){
            bufferedWriter.write("x="+position.getX());
            bufferedWriter.newLine();
            bufferedWriter.write("y="+position.getY());
            bufferedWriter.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Position load(){
        System.out.println("FileReaderManger2...");
        Position position = new Position(0,0);
        Map<String,String> map = new HashMap<>();
        //解析文件，把每行拆解为键值对放入map
        try(BufferedReader bufferedReader = new BufferedReader(new FileReader("data/game4.save"))){
             while (true){
                 String line = bufferedReader.readLine();
                 if(line == null){
                     break;
                 }
                 String[] arr = line.split("=");
                 String key = arr[0];
                 String value = arr[1];
                 map.put(key,value);
             }
        } catch (FileNotFoundException e) {
            System.out.println("没有读取到文件，使用默认值");
            return position;
        } catch (IOException e) {
            e.printStackTrace();
        }

        position.setX(Integer.parseInt(map.get("x")));
        position.setY(Integer.parseInt(map.get("y")));
        return position;
    }
}
